{% extends 'base.html' %}

{% block title %}{{ title }} - EasyTesting{% endblock %}

{% block header %}{{ title }}{% endblock %}

{% block content %}
<div class="row justify-content-center">
    <div class="col-md-10">
        <div class="card">
            <div class="card-body p-4">
                <form method="post">
                    {% csrf_token %}

                    <!-- 基本信息部分 -->
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <label for="{{ form.name.id_for_label }}" class="form-label fw-medium">测试用例名称</label>
                            {{ form.name.errors }}
                            <input type="text" class="form-control form-control-lg" id="{{ form.name.id_for_label }}" name="{{ form.name.html_name }}" value="{{ form.name.value|default:'' }}" required placeholder="输入测试用例名称">
                            <div class="form-text">测试用例名称</div>
                        </div>

                        <div class="col-md-6">
                            <label for="{{ form.project.id_for_label }}" class="form-label fw-medium">项目</label>
                            {{ form.project.errors }}
                            {% if form.project.field.widget.input_type == 'hidden' %}
                                {{ form.project }}
                                <input type="text" class="form-control form-control-lg" value="{{ form.project.value|default:''|stringformat:'s' }}" disabled>
                            {% else %}
                                <select class="form-select form-select-lg" id="{{ form.project.id_for_label }}" name="{{ form.project.html_name }}" required>
                                    {% for choice in form.project.field.choices %}
                                        <option value="{{ choice.0 }}" {% if form.project.value|stringformat:"s" == choice.0|stringformat:"s" %}selected{% endif %}>{{ choice.1 }}</option>
                                    {% endfor %}
                                </select>
                            {% endif %}
                            <div class="form-text">选择测试用例关联的项目</div>
                        </div>
                    </div>

                    <div class="mb-4">
                        <label for="{{ form.group.id_for_label }}" class="form-label fw-medium">分组</label>
                        {{ form.group.errors }}
                        <select class="form-select" id="{{ form.group.id_for_label }}" name="{{ form.group.html_name }}">
                            <option value="">暂无分组</option>
                            {% for choice in form.group.field.choices %}
                                {% if choice.0 %}
                                    <option value="{{ choice.0 }}" {% if form.group.value|stringformat:"s" == choice.0|stringformat:"s" %}selected{% endif %}>{{ choice.1 }}</option>
                                {% endif %}
                            {% endfor %}
                        </select>
                        <div class="form-text">选择测试用例的分组 (可选)</div>
                    </div>

                    <div class="mb-4">
                        <label for="{{ form.description.id_for_label }}" class="form-label fw-medium">描述</label>
                        {{ form.description.errors }}
                        <textarea class="form-control" id="{{ form.description.id_for_label }}" name="{{ form.description.html_name }}" rows="3" placeholder="描述测试用例...">{{ form.description.value|default:'' }}</textarea>
                        <div class="form-text">描述测试用例</div>
                    </div>

                    <div class="row mb-4">
                        <div class="col-md-3">
                            <label for="{{ form.request_method.id_for_label }}" class="form-label fw-medium">请求方式</label>
                            {{ form.request_method.errors }}
                            <select class="form-select" id="{{ form.request_method.id_for_label }}" name="{{ form.request_method.html_name }}" required>
                                {% for choice in form.request_method.field.choices %}
                                    <option value="{{ choice.0 }}" {% if form.request_method.value == choice.0 %}selected{% endif %}>{{ choice.0 }}</option>
                                {% endfor %}
                            </select>
                        </div>

                        <div class="col-md-6">
                            <label for="{{ form.request_url.id_for_label }}" class="form-label fw-medium">请求 URL</label>
                            {{ form.request_url.errors }}
                            <input type="text" class="form-control" id="{{ form.request_url.id_for_label }}" name="{{ form.request_url.html_name }}" value="{{ form.request_url.value|default:'' }}" required placeholder="/api/endpoint">
                            <div class="form-text">url路径</div>
                        </div>

                        <div class="col-md-3">
                            <label for="{{ form.expected_status_code.id_for_label }}" class="form-label fw-medium">预期状态码</label>
                            {{ form.expected_status_code.errors }}
                            <input type="number" class="form-control" id="{{ form.expected_status_code.id_for_label }}" name="{{ form.expected_status_code.html_name }}" value="{{ form.expected_status_code.value|default:'200' }}" required>
                        </div>
                    </div>

                    <!-- 请求参数表格 -->
                    <div class="mb-4">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <label class="form-label fw-medium mb-0">请求参数</label>
                            <div class="btn-group" role="group">

                                <button type="button" class="btn btn-sm btn-outline-secondary active" id="toggle-params-table-view-btn" title="Switch to table view">
                                    <i class="bi bi-table"></i> Table
                                </button>
                                <button type="button" class="btn btn-sm btn-outline-secondary" id="toggle-params-text-view-btn" title="Switch to text view">
                                    <i class="bi bi-file-text"></i> Text Mode
                                </button>
                            </div>
                        </div>


                        <div id="params-text-container" style="display: none;">
                            <div class="card">
                                <div class="card-body">
                                    <textarea class="form-control font-monospace" id="params-text-area" rows="8" placeholder="每行一个参数，格式为: key:value"></textarea>
                                    <div class="form-text mt-2">文本模式 - 每行一个参数，格式为: key:value</div>
                                </div>
                            </div>
                        </div>

                        <div id="params-table-container">
                            <div class="card">
                                <div class="card-body p-0">
                                    <div class="table-responsive">
                                        <table class="table table-bordered params-table mb-0">
                                            <thead class="bg-light">
                                                <tr>
                                                    <th style="width: 40px;" class="text-center">
                                                        <input type="checkbox" class="form-check-input" id="select-all-url-params" checked>
                                                    </th>
                                                    <th style="width: 30%;">Key</th>
                                                    <th>Value</th>
                                                    <th style="width: 30%;">Description</th>
                                                    <th style="width: 40px;" class="text-center">
                                                        <button type="button" class="btn btn-sm btn-link p-0" id="bulk-edit-params-btn" title="Bulk Edit">
                                                            <i class="bi bi-pencil-square"></i>
                                                        </button>
                                                    </th>
                                                </tr>
                                            </thead>
                                            <tbody id="url-params-container">
                                                <!-- 参数行将通过JavaScript动态添加 -->
                                            </tbody>
                                            <tfoot>
                                                <tr>
                                                    <td colspan="5">
                                                        <button type="button" class="btn btn-sm btn-outline-secondary w-100" id="add-url-param-btn">
                                                            <i class="bi bi-plus-lg"></i> Add Parameter
                                                        </button>
                                                    </td>
                                                </tr>
                                            </tfoot>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 请求头表格 -->
                    <div class="mb-4">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <label class="form-label fw-medium mb-0">请求头</label>
                            <div>
{#                                <button type="button" class="btn btn-sm btn-outline-secondary me-2" id="headers-preset-btn">#}
{#                                    Presets <i class="bi bi-chevron-down"></i>#}
{#                                </button>#}
                                <button type="button" class="btn btn-sm btn-outline-secondary me-2" id="bulk-edit-headers-btn">
                                    Bulk Edit
                                </button>

                                <button type="button" class="btn btn-sm btn-outline-secondary me-2" id="toggle-headers-mode-btn" title="Switch between table and text mode">
                                    Key-Value Edit
                                </button>
                                <button type="button" class="btn btn-sm btn-outline-secondary" id="toggle-headers-table">
                                    <i class="bi bi-chevron-down" id="toggle-headers-icon"></i>
                                </button>
                            </div>
                        </div>


                        <div id="headers-text-container" style="display: none;">
                            <textarea class="form-control font-monospace" id="headers-text-area" rows="6" placeholder="每行一个请求头，格式为: Key: Value"></textarea>
                            <div class="form-text mt-2">文本模式 - 每行一个请求头，格式为: Key: Value</div>
                        </div>

                        <div id="headers-table-container">
                            <div class="card">
                                <div class="card-body p-0">
                                    <div class="table-responsive">
                                        <table class="table table-bordered headers-table mb-0">
                                            <thead class="bg-light">
                                                <tr>
                                                    <th style="width: 40px;" class="text-center">
                                                        <input type="checkbox" class="form-check-input" id="select-all-headers" checked>
                                                    </th>
                                                    <th style="width: 30%;">Key</th>
                                                    <th>Value</th>
                                                    <th style="width: 30%;">Description</th>
                                                    <th style="width: 40px;" class="text-center">
                                                        <i class="bi bi-pencil-square"></i>
                                                    </th>
                                                </tr>
                                            </thead>
                                            <tbody id="headers-container">
                                                <!-- 头部行将通过JavaScript动态添加 -->
                                            </tbody>
                                            <tfoot>
                                                <tr>
                                                    <td colspan="5">
                                                        <button type="button" class="btn btn-sm btn-outline-secondary w-100" id="add-header-btn">
                                                            <i class="bi bi-plus-lg"></i> Add Header
                                                        </button>
                                                    </td>
                                                </tr>
                                            </tfoot>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 隐藏的原始文本区域，用于表单提交 -->
                        {{ form.request_headers_json.errors }}
                        <textarea class="form-control d-none" id="{{ form.request_headers_json.id_for_label }}" name="{{ form.request_headers_json.html_name }}">{{ form.request_headers_json.value|default:"" }}</textarea>
                        <div class="form-text mt-2">输入JSON格式的请求头, 例如 {"Content-Type": "application/json"}</div>
                    </div>

                    <!-- 请求体格式 -->
                    <div class="mb-4">
                        <label class="form-label fw-medium">请求体格式</label>
                        {{ form.request_body_format.errors }}
                        <div class="d-flex">
                            <div class="form-check me-4">
                                <input class="form-check-input" type="radio" name="{{ form.request_body_format.html_name }}" id="format_json" value="json" {% if form.request_body_format.value == 'json' or not form.request_body_format.value %}checked{% endif %} onchange="toggleBodyFormat()">
                                <label class="form-check-label" for="format_json">
                                    JSON
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="{{ form.request_body_format.html_name }}" id="format_form_data" value="form-data" {% if form.request_body_format.value == 'form-data' %}checked{% endif %} onchange="toggleBodyFormat()">
                                <label class="form-check-label" for="format_form_data">
                                    Form Data
                                </label>
                            </div>
                        </div>
                    </div>

                    <!-- JSON 请求体 -->
                    <div id="json_body_container" class="mb-4" {% if form.request_body_format.value == 'form-data' %}style="display: none;"{% endif %}>
                        <label for="{{ form.request_body_json.id_for_label }}" class="form-label fw-medium">请求体 (JSON)</label>
                        {{ form.request_body_json.errors }}
                        <textarea class="form-control font-monospace" id="{{ form.request_body_json.id_for_label }}" name="{{ form.request_body_json.html_name }}" rows="6" placeholder='{"name": "Test User", "email": "test@example.com"}'>{{ form.request_body_json.value|default:"" }}</textarea>
                        <div class="form-text">{{ form.request_body_json.help_text }}</div>
                    </div>

                    <!-- Form Data 请求体 -->
                    <div id="form_data_container" class="mb-4" {% if form.request_body_format.value != 'form-data' %}style="display: none;"{% endif %}>
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <label class="form-label fw-medium mb-0">请求体 (Form Data)</label>
                            <div>

                                <button type="button" class="btn btn-sm btn-outline-secondary me-2" id="toggle-form-data-mode-btn" title="Switch between table and text mode">
                                    Key-Value Edit
                                </button>
                                <button type="button" class="btn btn-sm btn-outline-secondary" id="toggle-form-data-table">
                                    <i class="bi bi-chevron-down" id="toggle-form-data-icon"></i>
                                </button>
                            </div>
                        </div>
                        {{ form.request_body_form_data.errors }}


                        <div id="form-data-text-container" style="display: none;">
                            <textarea class="form-control font-monospace" id="form-data-text-area" rows="8" placeholder="每行一个参数，格式为: key=value"></textarea>
                            <div class="form-text mt-2">文本模式 - 每行一个参数，格式为: key=value</div>
                        </div>

                        <div id="form-data-table-container">
                            <div class="card">
                                <div class="card-body p-0">
                                    <div class="table-responsive">
                                        <table class="table table-bordered form-data-table mb-0">
                                            <thead class="bg-light">
                                                <tr>
                                                    <th style="width: 40px;" class="text-center">
                                                        <input type="checkbox" class="form-check-input" id="select-all-form-data" checked>
                                                    </th>
                                                    <th style="width: 30%;">Key</th>
                                                    <th style="width: 15%;">Type</th>
                                                    <th>Value</th>
                                                    <th style="width: 20%;">Description</th>
                                                    <th style="width: 40px;" class="text-center">
                                                        <i class="bi bi-pencil-square"></i>
                                                    </th>
                                                </tr>
                                            </thead>
                                            <tbody id="form-data-params">
                                                <!-- 参数行将通过JavaScript动态添加 -->
                                            </tbody>
                                            <tfoot>
                                                <tr>
                                                    <td colspan="6">
                                                        <button type="button" class="btn btn-sm btn-outline-secondary w-100" id="add-form-data-btn">
                                                            <i class="bi bi-plus-lg"></i> Add Parameter
                                                        </button>
                                                    </td>
                                                </tr>
                                            </tfoot>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 隐藏的原始文本区域，用于表单提交 -->
                        <textarea class="form-control d-none" id="{{ form.request_body_form_data.id_for_label }}" name="{{ form.request_body_form_data.html_name }}">{{ form.request_body_form_data.value|default:"" }}</textarea>
                        <div class="form-text mt-2">输入form-data格式的数据，每行一个参数，格式为key=value</div>
                    </div>

                    <!-- 提取参数表格 -->
                    <div class="mb-4">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <label class="form-label fw-medium mb-0">提取参数</label>
                            <div>
                                <button type="button" class="btn btn-sm btn-outline-secondary me-2" id="bulk-edit-extract-btn">
                                    Bulk Edit
                                </button>
                                <!-- Add Key-Value Edit toggle button for extract text mode -->
                                <button type="button" class="btn btn-sm btn-outline-secondary me-2" id="toggle-extract-mode-btn" title="Switch between table and text mode">
                                    Key-Value Edit
                                </button>
                                <button type="button" class="btn btn-sm btn-outline-secondary" id="toggle-extract-table">
                                    <i class="bi bi-chevron-down" id="toggle-extract-icon"></i>
                                </button>
                            </div>
                        </div>


                        <div id="extract-text-container" style="display: none;">
                            <textarea class="form-control font-monospace" id="extract-text-area" rows="6" placeholder="JSON格式，每行一个提取参数"></textarea>
                            <div class="form-text mt-2">文本模式 - JSON格式: [{"name": "param_name", "path": "$.data.field"}]</div>
                        </div>

                        <div id="extract-table-container">
                            <div class="card">
                                <div class="card-body p-0">
                                    <div class="table-responsive">
                                        <table class="table table-bordered extract-table mb-0">
                                            <thead class="bg-light">
                                                <tr>
                                                    <th style="width: 40px;" class="text-center">
                                                        <input type="checkbox" class="form-check-input" id="select-all-extract" checked>
                                                    </th>
                                                    <th style="width: 25%;">Name</th>
                                                    <th style="width: 35%;">Path</th>
                                                    <th>Description</th>
                                                    <th style="width: 40px;" class="text-center">
                                                        <i class="bi bi-pencil-square"></i>
                                                    </th>
                                                </tr>
                                            </thead>
                                            <tbody id="extract-container">
                                                <!-- 提取参数行将通过JavaScript动态添加 -->
                                            </tbody>
                                            <tfoot>
                                                <tr>
                                                    <td colspan="5">
                                                        <button type="button" class="btn btn-sm btn-outline-secondary w-100" id="add-extract-btn">
                                                            <i class="bi bi-plus-lg"></i> Add Extract Parameter
                                                        </button>
                                                    </td>
                                                </tr>
                                            </tfoot>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 隐藏的原始文本区域，用于表单提交 -->
                        {{ form.extract_params_json.errors }}
                        <textarea class="form-control d-none" id="{{ form.extract_params_json.id_for_label }}" name="{{ form.extract_params_json.html_name }}">{{ form.extract_params_json.value|default:"" }}</textarea>
                        <div class="form-text mt-2">输入json格式的提取参数, 例如, [{"name": "token", "path": "$.data.token"}]</div>
                    </div>

                    <!-- 断言表格 -->
                    <div class="mb-4">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <label class="form-label fw-medium mb-0">断言</label>
                            <div>
                                <button type="button" class="btn btn-sm btn-outline-secondary me-2" id="bulk-edit-validation-btn">
                                    Bulk Edit
                                </button>

                                <button type="button" class="btn btn-sm btn-outline-secondary me-2" id="toggle-validation-mode-btn" title="Switch between table and text mode">
                                    Key-Value Edit
                                </button>
                                <button type="button" class="btn btn-sm btn-outline-secondary" id="toggle-validation-table">
                                    <i class="bi bi-chevron-down" id="toggle-validation-icon"></i>
                                </button>
                            </div>
                        </div>


                        <div id="validation-text-container" style="display: none;">
                            <textarea class="form-control font-monospace" id="validation-text-area" rows="6" placeholder="JSON格式，每行一个断言规则"></textarea>
                            <div class="form-text mt-2">文本模式 - JSON格式: [{"eq": ["$.data.id", 1]}]</div>
                        </div>

                        <div id="validation-table-container">
                            <div class="card">
                                <div class="card-body p-0">
                                    <div class="table-responsive">
                                        <table class="table table-bordered validation-table mb-0">
                                            <thead class="bg-light">
                                                <tr>
                                                    <th style="width: 40px;" class="text-center">
                                                        <input type="checkbox" class="form-check-input" id="select-all-validation" checked>
                                                    </th>
                                                    <th style="width: 20%;">Validator</th>
                                                    <th style="width: 30%;">Path/Expected</th>
                                                    <th style="width: 30%;">Value</th>
                                                    <th>Description</th>
                                                    <th style="width: 40px;" class="text-center">
                                                        <i class="bi bi-pencil-square"></i>
                                                    </th>
                                                </tr>
                                            </thead>
                                            <tbody id="validation-container">
                                                <!-- 验证规则行将通过JavaScript动态添加 -->
                                            </tbody>
                                            <tfoot>
                                                <tr>
                                                    <td colspan="6">
                                                        <button type="button" class="btn btn-sm btn-outline-secondary w-100" id="add-validation-btn">
                                                            <i class="bi bi-plus-lg"></i> Add Validation Rule
                                                        </button>
                                                    </td>
                                                </tr>
                                            </tfoot>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 隐藏的原始文本区域，用于表单提交 -->
                        {{ form.validation_rules_json.errors }}
                        <textarea class="form-control d-none" id="{{ form.validation_rules_json.id_for_label }}" name="{{ form.validation_rules_json.html_name }}">{{ form.validation_rules_json.value|default:"" }}</textarea>
                        <div class="form-text mt-2">输入json格式的验证规则, 例如, [{"eq": ["$.data.id", 1]}]</div>
                    </div>

                    <!-- 表单按钮 -->
                    <div class="d-flex justify-content-between mt-4">
                        <a href="{% if request.GET.project %}{% url 'project_detail' pk=request.GET.project %}{% else %}{% url 'test_case_list' %}{% endif %}" class="btn btn-outline-secondary">
                            <i class="bi bi-arrow-left"></i> 取消
                        </a>
                        <button type="submit" class="btn btn-primary px-4">
                            <i class="bi bi-check-lg"></i> 保存
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- 批量编辑模态框 -->
<div class="modal fade" id="bulkEditModal" tabindex="-1" aria-labelledby="bulkEditLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="bulkEditLabel">批量编辑</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-info" role="alert">
                    已选择 <strong id="selectedCount">0</strong> 项
                </div>

                <!-- 编辑字段选择 -->
                <div class="mb-4">
                    <label class="form-label fw-medium">选择要编辑的字段</label>
                    <div id="bulkEditFields" class="border rounded p-3 bg-light">
                        <!-- 动态生成的复选框 -->
                    </div>
                </div>

                <!-- 编辑值输入 -->
                <div id="bulkEditInputs">
                    <!-- 动态生成的输入字段 -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="applyBulkEditBtn">应用</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    const BulkEditManager = {
        currentTable: null,
        selectedRows: [],
        fieldConfigs: {
            'url-params': {
                fields: ['key', 'value', 'description'],
                labels: { key: 'Key', value: 'Value', description: 'Description' },
                getRow: (elem) => elem.closest('tr'),
                getCheckbox: (row) => row.querySelector('.url-param-checkbox'),
                getFields: (row) => ({
                    key: row.querySelector('.param-key'),
                    value: row.querySelector('.param-value'),
                    description: row.querySelector('.param-description')
                })
            },
            'headers': {
                fields: ['key', 'value', 'description'],
                labels: { key: 'Key', value: 'Value', description: 'Description' },
                getRow: (elem) => elem.closest('tr'),
                getCheckbox: (row) => row.querySelector('.header-checkbox'),
                getFields: (row) => ({
                    key: row.querySelector('.header-key'),
                    value: row.querySelector('.header-value'),
                    description: row.querySelector('.header-description')
                })
            },
            'form-data': {
                fields: ['key', 'type', 'value', 'description'],
                labels: { key: 'Key', type: 'Type', value: 'Value', description: 'Description' },
                getRow: (elem) => elem.closest('tr'),
                getCheckbox: (row) => row.querySelector('input[type="checkbox"]'),
                getFields: (row) => ({
                    key: row.querySelector('.form-key'),
                    type: row.querySelector('.form-type'),
                    value: row.querySelector('.form-value'),
                    description: row.querySelector('.form-description')
                })
            },
            'extract': {
                fields: ['name', 'path', 'description'],
                labels: { name: 'Name', path: 'Path', description: 'Description' },
                getRow: (elem) => elem.closest('tr'),
                getCheckbox: (row) => row.querySelector('.extract-checkbox'),
                getFields: (row) => ({
                    name: row.querySelector('.extract-name'),
                    path: row.querySelector('.extract-path'),
                    description: row.querySelector('.extract-description')
                })
            },
            'validation': {
                fields: ['validator', 'path', 'value', 'description'],
                labels: { validator: 'Validator', path: 'Path/Expected', value: 'Value', description: 'Description' },
                getRow: (elem) => elem.closest('tr'),
                getCheckbox: (row) => row.querySelector('.validation-checkbox'),
                getFields: (row) => ({
                    validator: row.querySelector('.validation-type'),
                    path: row.querySelector('.validation-path'),
                    value: row.querySelector('.validation-value'),
                    description: row.querySelector('.validation-description')
                })
            }
        },

        show(tableType, containerSelector) {
            this.currentTable = tableType;
            const container = document.querySelector(containerSelector);
            const config = this.fieldConfigs[tableType];

            // 获取选中的行
            this.selectedRows = [];
            const checkboxes = container.querySelectorAll('input[type="checkbox"]');
            checkboxes.forEach(checkbox => {
                if (checkbox.checked && !checkbox.closest('thead')) {
                    const row = config.getRow(checkbox);
                    this.selectedRows.push(row);
                }
            });

            // 更新计数
            document.getElementById('selectedCount').textContent = this.selectedRows.length;

            if (this.selectedRows.length === 0) {
                alert('请先选择至少一项');
                return;
            }

            // 生成字段选择器
            this.generateFieldSelectors(config);

            // 显示模态框
            const modal = new bootstrap.Modal(document.getElementById('bulkEditModal'));
            modal.show();
        },

        generateFieldSelectors(config) {
            const fieldsContainer = document.getElementById('bulkEditFields');
            fieldsContainer.innerHTML = '';

            config.fields.forEach(field => {
                const div = document.createElement('div');
                div.className = 'form-check';
                div.innerHTML = `
                    <input class="form-check-input bulk-field-checkbox" type="checkbox" id="field_${field}" value="${field}">
                    <label class="form-check-label" for="field_${field}">
                        ${config.labels[field]}
                    </label>
                `;
                fieldsContainer.appendChild(div);
            });

            // 生成输入字段
            this.generateInputFields(config);

            // 添加事件监听
            document.querySelectorAll('.bulk-field-checkbox').forEach(checkbox => {
                checkbox.addEventListener('change', () => this.generateInputFields(config));
            });
        },

        generateInputFields(config) {
            const inputsContainer = document.getElementById('bulkEditInputs');
            inputsContainer.innerHTML = '';

            document.querySelectorAll('.bulk-field-checkbox:checked').forEach(checkbox => {
                const field = checkbox.value;
                const label = config.labels[field];
                const div = document.createElement('div');
                div.className = 'mb-3';

                let input = '';
                if (field === 'type') {
                    // 针对Form Data的type字段
                    input = `
                        <label class="form-label" for="input_${field}">${label}</label>
                        <select class="form-select bulk-input" id="input_${field}" data-field="${field}">
                            <option value="Text">Text</option>
                            <option value="File">File</option>
                            <option value="Number">Number</option>
                        </select>
                    `;
                } else if (field === 'validator') {
                    // 针对断言的validator字段
                    input = `
                        <label class="form-label" for="input_${field}">${label}</label>
                        <select class="form-select bulk-input" id="input_${field}" data-field="${field}">
                            <option value="eq">Equals</option>
                            <option value="ne">Not Equals</option>
                            <option value="gt">Greater Than</option>
                            <option value="lt">Less Than</option>
                            <option value="contains">Contains</option>
                            <option value="regex">Regex</option>
                        </select>
                    `;
                } else {
                    input = `
                        <label class="form-label" for="input_${field}">${label}</label>
                        <input type="text" class="form-control bulk-input" id="input_${field}" data-field="${field}" placeholder="输入新值...">
                    `;
                }

                div.innerHTML = input;
                inputsContainer.appendChild(div);
            });
        },

        applyChanges() {
            const config = this.fieldConfigs[this.currentTable];
            const updates = {};

            document.querySelectorAll('.bulk-input').forEach(input => {
                const field = input.dataset.field;
                updates[field] = input.value;
            });

            if (Object.keys(updates).length === 0) {
                alert('请至少选择一个要编辑的字段');
                return;
            }

            // 应用更改到选中的行
            this.selectedRows.forEach(row => {
                const fields = config.getFields(row);
                Object.keys(updates).forEach(field => {
                    if (fields[field]) {
                        fields[field].value = updates[field];
                        // 触发change事件以更新关联的文本区域
                        fields[field].dispatchEvent(new Event('input', { bubbles: true }));
                    }
                });
            });

            // 关闭模态框
            bootstrap.Modal.getInstance(document.getElementById('bulkEditModal')).hide();
            alert(`已成功编辑 ${this.selectedRows.length} 项`);
        }
    };

    // URL参数表格初始化
    function initUrlParamsTable() {
        const urlInput = document.getElementById('{{ form.request_url.id_for_label }}');
        const paramsContainer = document.getElementById('url-params-container');
        const addParamBtn = document.getElementById('add-url-param-btn');
        const selectAllCheckbox = document.getElementById('select-all-url-params');
        const bulkEditBtn = document.getElementById('bulk-edit-params-btn');
        const toggleParamsTableViewBtn = document.getElementById('toggle-params-table-view-btn');
        const toggleParamsTextViewBtn = document.getElementById('toggle-params-text-view-btn');
        const paramsTextContainer = document.getElementById('params-text-container');
        const paramsTableContainer = document.getElementById('params-table-container');
        const paramsTextArea = document.getElementById('params-text-area');

        let isUpdatingUrl = false;

        function parseUrlParams(url) {
            const params = [];
            if (!url) return params;
            const queryStringMatch = url.match(/\?([^#]*)/);
            if (!queryStringMatch) return params;
            const queryString = queryStringMatch[1];
            const searchParams = new URLSearchParams(queryString);
            searchParams.forEach((value, key) => {
                params.push({ key, value, description: '' });
            });
            return params;
        }

        function buildQueryString() {
            const rows = paramsContainer.querySelectorAll('tr');
            const searchParams = new URLSearchParams();
            rows.forEach(row => {
                const checkbox = row.querySelector('input[type="checkbox"]');
                if (checkbox && checkbox.checked) {
                    const keyInput = row.querySelector('.param-key');
                    const valueInput = row.querySelector('.param-value');
                    if (keyInput && valueInput && keyInput.value.trim()) {
                        searchParams.append(keyInput.value.trim(), valueInput.value.trim());
                    }
                }
            });
            return searchParams.toString();
        }

        function updateUrlInput() {
            if (isUpdatingUrl) return;
            isUpdatingUrl = true;
            try {
                let url = urlInput.value || '';
                const queryString = buildQueryString();
                url = url.replace(/\?[^#]*/, '');
                if (queryString) url = `${url}?${queryString}`;
                urlInput.value = url;
            } finally {
                isUpdatingUrl = false;
            }
        }

        function addParamRow(param = { key: '', value: '', description: '' }) {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td class="text-center align-middle">
                    <input type="checkbox" class="form-check-input url-param-checkbox" checked>
                </td>
                <td><input type="text" class="form-control param-key" value="${param.key}" placeholder="Key"></td>
                <td><input type="text" class="form-control param-value" value="${param.value}" placeholder="Value"></td>
                <td><input type="text" class="form-control param-description" value="${param.description}" placeholder="Description"></td>
                <td class="text-center align-middle">
                    <button type="button" class="btn btn-sm btn-link text-danger p-0 delete-param-btn">
                        <i class="bi bi-trash"></i>
                    </button>
                </td>
            `;

            const keyInput = row.querySelector('.param-key');
            const valueInput = row.querySelector('.param-value');
            const checkbox = row.querySelector('.url-param-checkbox');
            const deleteBtn = row.querySelector('.delete-param-btn');

            keyInput.addEventListener('input', updateUrlInput);
            valueInput.addEventListener('input', updateUrlInput);
            checkbox.addEventListener('change', updateUrlInput);
            deleteBtn.addEventListener('click', () => {
                row.remove();
                updateUrlInput();
            });

            paramsContainer.appendChild(row);
        }

        function updateParamsTable() {
            if (isUpdatingUrl) return;
            paramsContainer.innerHTML = '';
            const params = parseUrlParams(urlInput.value);
            if (params.length > 0) {
                params.forEach(param => addParamRow(param));
            } else {
                addParamRow();
            }
        }

        function parseParamsFromTextArea() {
            const params = [];
            const lines = paramsTextArea.value.trim().split('\n');
            for (const line of lines) {
                if (line.includes(':')) {
                    const [key, value] = line.split(':', 2);
                    params.push({
                        key: key.trim(),
                        value: value.trim(),
                        description: ''
                    });
                }
            }
            if (params.length === 0) {
                params.push({ key: '', value: '', description: '' });
            }
            return params;
        }

        function updateParamsTextArea() {
            const rows = paramsContainer.querySelectorAll('tr');
            const lines = [];
            rows.forEach(row => {
                const checkbox = row.querySelector('input[type="checkbox"]');
                if (checkbox && checkbox.checked) {
                    const keyInput = row.querySelector('.param-key');
                    const valueInput = row.querySelector('.param-value');
                    if (keyInput && valueInput && keyInput.value.trim()) {
                        lines.push(`${keyInput.value.trim()}:${valueInput.value.trim()}`);
                    }
                }
            });
            paramsTextArea.value = lines.join('\n');
        }


        function toggleParamsMode(showTextMode) {
            if (showTextMode === undefined) {
                // Toggle based on current state
                showTextMode = paramsTableContainer.style.display !== 'none';
            }

            if (showTextMode) {
                // Switch to text mode
                paramsTextContainer.style.display = 'block';
                paramsTableContainer.style.display = 'none';
                paramsTextArea.value = '';
                const params = [];
                paramsContainer.querySelectorAll('tr').forEach(row => {
                    const keyInput = row.querySelector('.param-key');
                    const valueInput = row.querySelector('.param-value');
                    if (keyInput && valueInput && keyInput.value.trim() && valueInput.value.trim()) {
                        params.push(`${keyInput.value.trim()}:${valueInput.value.trim()}`);
                    }
                });
                paramsTextArea.value = params.join('\n');

                toggleParamsTextViewBtn.classList.add('active');
                toggleParamsTableViewBtn.classList.remove('active');
            } else {
                // Switch to table mode
                paramsTextContainer.style.display = 'none';
                paramsTableContainer.style.display = 'block';
                paramsContainer.innerHTML = '';
                const params = parseParamsFromTextArea();
                params.forEach(param => addParamRow(param));
                updateUrlInput();

                toggleParamsTextViewBtn.classList.remove('active');
                toggleParamsTableViewBtn.classList.add('active');
            }
        }

        updateParamsTable();
        urlInput.addEventListener('input', () => {
            if (!isUpdatingUrl) updateParamsTable();
        });
        addParamBtn.addEventListener('click', () => {
            addParamRow();
            updateUrlInput();
        });
        selectAllCheckbox.addEventListener('change', () => {
            paramsContainer.querySelectorAll('.url-param-checkbox').forEach(cb => {
                cb.checked = selectAllCheckbox.checked;
            });
            updateUrlInput();
        });
        bulkEditBtn.addEventListener('click', () => {
            BulkEditManager.show('url-params', '#url-params-container');
        });

        toggleParamsTableViewBtn.addEventListener('click', () => {
            if (paramsTableContainer.style.display === 'none') {
                toggleParamsMode(false);
            }
        });

        toggleParamsTextViewBtn.addEventListener('click', () => {
            if (paramsTextContainer.style.display === 'none') {
                toggleParamsMode(true);
            }
        });

        paramsTextArea.addEventListener('input', updateParamsTextArea);

    }

    // 请求头表格初始化
    function initHeadersTable() {
        const textarea = document.getElementById('{{ form.request_headers_json.id_for_label }}');
        const headersContainer = document.getElementById('headers-container');
        const addHeaderBtn = document.getElementById('add-header-btn');
        const selectAllCheckbox = document.getElementById('select-all-headers');
        const bulkEditBtn = document.getElementById('bulk-edit-headers-btn');

        function parseHeaders() {
            const headers = [];
            if (textarea.value) {
                try {
                    const headersObj = JSON.parse(textarea.value);
                    for (const [key, value] of Object.entries(headersObj)) {
                        headers.push({ key, value, description: '' });
                    }
                } catch (e) {
                    console.error('Error parsing headers:', e);
                }
            }
            if (headers.length === 0) {
                headers.push({ key: '', value: '', description: '' });
            }
            return headers;
        }

        function updateHeadersTextarea() {
            const rows = headersContainer.querySelectorAll('tr');
            const headers = {};
            rows.forEach(row => {
                const checkbox = row.querySelector('input[type="checkbox"]');
                if (checkbox && checkbox.checked) {
                    const keyInput = row.querySelector('.header-key');
                    const valueInput = row.querySelector('.header-value');
                    if (keyInput && valueInput && keyInput.value.trim()) {
                        headers[keyInput.value.trim()] = valueInput.value.trim();
                    }
                }
            });
            textarea.value = JSON.stringify(headers, null, 2);
        }

        function addHeaderRow(header = { key: '', value: '', description: '' }) {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td class="text-center align-middle">
                    <input type="checkbox" class="form-check-input header-checkbox" checked>
                </td>
                <td><input type="text" class="form-control header-key" value="${header.key}" placeholder="Key"></td>
                <td><input type="text" class="form-control header-value" value="${header.value}" placeholder="Value"></td>
                <td><input type="text" class="form-control header-description" value="${header.description}" placeholder="Description"></td>
                <td class="text-center align-middle">
                    <button type="button" class="btn btn-sm btn-link text-danger p-0 delete-header-btn">
                        <i class="bi bi-trash"></i>
                    </button>
                </td>
            `;

            const keyInput = row.querySelector('.header-key');
            const valueInput = row.querySelector('.header-value');
            const checkbox = row.querySelector('.header-checkbox');
            const deleteBtn = row.querySelector('.delete-header-btn');

            keyInput.addEventListener('input', updateHeadersTextarea);
            valueInput.addEventListener('input', updateHeadersTextarea);
            checkbox.addEventListener('change', updateHeadersTextarea);
            deleteBtn.addEventListener('click', () => {
                row.remove();
                updateHeadersTextarea();
            });

            headersContainer.appendChild(row);
        }

        const headers = parseHeaders();
        headers.forEach(header => addHeaderRow(header));

        addHeaderBtn.addEventListener('click', () => {
            addHeaderRow();
            updateHeadersTextarea();
        });
        selectAllCheckbox.addEventListener('change', () => {
            headersContainer.querySelectorAll('.header-checkbox').forEach(cb => {
                cb.checked = selectAllCheckbox.checked;
            });
            updateHeadersTextarea();
        });
        bulkEditBtn.addEventListener('click', () => {
            BulkEditManager.show('headers', '#headers-container');
        });

        const headersTableContainer = document.getElementById('headers-table-container');
        const headersTextContainer = document.getElementById('headers-text-container');
        const headersTextArea = document.getElementById('headers-text-area');
        const toggleHeadersModeBtn = document.getElementById('toggle-headers-mode-btn');

        function updateHeadersTextArea() {
            const headers = {};
            headersContainer.querySelectorAll('tr').forEach(row => {
                const checkbox = row.querySelector('input[type="checkbox"]');
                if (checkbox && checkbox.checked) {
                    const keyInput = row.querySelector('.header-key');
                    const valueInput = row.querySelector('.header-value');
                    if (keyInput && valueInput && keyInput.value.trim()) {
                        headers[keyInput.value.trim()] = valueInput.value.trim();
                    }
                }
            });
            let textLines = [];
            for (const [key, value] of Object.entries(headers)) {
                textLines.push(`${key}: ${value}`);
            }
            headersTextArea.value = textLines.join('\n');
        }

        function parseHeadersFromText() {
            const lines = headersTextArea.value.trim().split('\n');
            const headers = [];
            lines.forEach(line => {
                if (line.includes(':')) {
                    const [key, ...valueParts] = line.split(':');
                    headers.push({ key: key.trim(), value: valueParts.join(':').trim(), description: '' });
                }
            });
            return headers;
        }

        toggleHeadersModeBtn.addEventListener('click', () => {
            const isTableVisible = headersTableContainer.style.display !== 'none';
            if (isTableVisible) {
                // Switch to text mode
                updateHeadersTextArea();
                headersTableContainer.style.display = 'none';
                headersTextContainer.style.display = 'block';
                toggleHeadersModeBtn.textContent = 'Table Edit';
            } else {
                // Switch to table mode
                headersContainer.innerHTML = '';
                const headers = parseHeadersFromText();
                if (headers.length > 0) {
                    headers.forEach(header => addHeaderRow(header));
                } else {
                    addHeaderRow();
                }
                updateHeadersTextarea();
                headersTableContainer.style.display = 'block';
                headersTextContainer.style.display = 'none';
                toggleHeadersModeBtn.textContent = 'Key-Value Edit';
            }
        });

        document.getElementById('toggle-headers-table').addEventListener('click', () => {
            const container = document.getElementById('headers-table-container');
            container.style.display = container.style.display === 'none' ? 'block' : 'none';
        });
    }

    // Form Data 表格初始化
    function initFormDataTable() {
        const textarea = document.getElementById('{{ form.request_body_form_data.id_for_label }}');
        const paramsContainer = document.getElementById('form-data-params');
        const addParamBtn = document.getElementById('add-form-data-btn');
        const selectAllCheckbox = document.getElementById('select-all-form-data');

        function parseParams() {
            const params = [];
            if (textarea.value) {
                const lines = textarea.value.trim().split('\n');
                for (const line of lines) {
                    if (line.includes('=')) {
                        const [key, value] = line.split('=', 2);
                        params.push({
                            key: key.trim(),
                            value: value.trim(),
                            type: 'Text',
                            description: ''
                        });
                    }
                }
            }
            if (params.length === 0) {
                params.push({
                    key: '',
                    value: '',
                    type: 'Text',
                    description: ''
                });
            }
            return params;
        }

        function updateTextarea() {
            const rows = paramsContainer.querySelectorAll('tr');
            const lines = [];
            rows.forEach(row => {
                const checkbox = row.querySelector('input[type="checkbox"]');
                if (checkbox && checkbox.checked) {
                    const keyInput = row.querySelector('.form-key');
                    const valueInput = row.querySelector('.form-value');
                    if (keyInput && valueInput && keyInput.value.trim()) {
                        lines.push(`${keyInput.value.trim()}=${valueInput.value.trim()}`);
                    }
                }
            });
            textarea.value = lines.join('\n');
        }

        function addParamRow(param = { key: '', value: '', type: 'Text', description: '' }) {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td class="text-center align-middle">
                    <input type="checkbox" class="form-check-input" checked>
                </td>
                <td><input type="text" class="form-control form-key" value="${param.key}" placeholder="Key"></td>
                <td>
                    <select class="form-select form-type">
                        <option value="Text" ${param.type === 'Text' ? 'selected' : ''}>Text</option>
                        <option value="File" ${param.type === 'File' ? 'selected' : ''}>File</option>
                        <option value="Number" ${param.type === 'Number' ? 'selected' : ''}>Number</option>
                    </select>
                </td>
                <td><input type="text" class="form-control form-value" value="${param.value}" placeholder="Value"></td>
                <td><input type="text" class="form-control form-description" value="${param.description}" placeholder="Description"></td>
                <td class="text-center align-middle">
                    <button type="button" class="btn btn-sm btn-link text-danger p-0 delete-param-btn">
                        <i class="bi bi-trash"></i>
                    </button>
                </td>
            `;

            const inputs = row.querySelectorAll('input, select');
            inputs.forEach(input => input.addEventListener('change', updateTextarea));

            const deleteBtn = row.querySelector('.delete-param-btn');
            deleteBtn.addEventListener('click', () => {
                row.remove();
                updateTextarea();
            });

            paramsContainer.appendChild(row);
        }

        const params = parseParams();
        params.forEach(param => addParamRow(param));

        addParamBtn.addEventListener('click', () => {
            addParamRow();
            updateTextarea();
        });
        selectAllCheckbox.addEventListener('change', () => {
            paramsContainer.querySelectorAll('input[type="checkbox"]').forEach(cb => {
                cb.checked = selectAllCheckbox.checked;
            });
        });
        // bulkEditBtn is not present for form-data, add it if needed

        const formDataTableContainer = document.getElementById('form-data-table-container');
        const formDataTextContainer = document.getElementById('form-data-text-container');
        const formDataTextArea = document.getElementById('form-data-text-area');
        const toggleFormDataModeBtn = document.getElementById('toggle-form-data-mode-btn');

        function updateFormDataTextArea() {
            const lines = [];
            paramsContainer.querySelectorAll('tr').forEach(row => {
                const checkbox = row.querySelector('input[type="checkbox"]');
                if (checkbox && checkbox.checked) {
                    const keyInput = row.querySelector('.form-key');
                    const valueInput = row.querySelector('.form-value');
                    if (keyInput && valueInput && keyInput.value.trim()) {
                        lines.push(`${keyInput.value.trim()}=${valueInput.value.trim()}`);
                    }
                }
            });
            formDataTextArea.value = lines.join('\n');
        }

        function parseFormDataFromText() {
            const lines = formDataTextArea.value.trim().split('\n');
            const params = [];
            lines.forEach(line => {
                if (line.includes('=')) {
                    const [key, value] = line.split('=', 2);
                    params.push({ key: key.trim(), value: value.trim(), type: 'Text', description: '' });
                }
            });
            return params;
        }

        toggleFormDataModeBtn.addEventListener('click', () => {
            const isTableVisible = formDataTableContainer.style.display !== 'none';
            if (isTableVisible) {
                // Switch to text mode
                updateFormDataTextArea();
                formDataTableContainer.style.display = 'none';
                formDataTextContainer.style.display = 'block';
                toggleFormDataModeBtn.textContent = 'Table Edit';
            } else {
                // Switch to table mode
                paramsContainer.innerHTML = '';
                const params = parseFormDataFromText();
                if (params.length > 0) {
                    params.forEach(param => addParamRow(param));
                } else {
                    addParamRow();
                }
                updateTextarea();
                formDataTableContainer.style.display = 'block';
                formDataTextContainer.style.display = 'none';
                toggleFormDataModeBtn.textContent = 'Key-Value Edit';
            }
        });

        document.getElementById('toggle-form-data-table').addEventListener('click', () => {
            const container = document.getElementById('form-data-table-container');
            container.style.display = container.style.display === 'none' ? 'block' : 'none';
        });
    }

    // 提取参数表格初始化
    function initExtractParamsTable() {
        const textarea = document.getElementById('{{ form.extract_params_json.id_for_label }}');
        const container = document.getElementById('extract-container');
        const addBtn = document.getElementById('add-extract-btn');
        const selectAllCheckbox = document.getElementById('select-all-extract');
        const bulkEditBtn = document.getElementById('bulk-edit-extract-btn');

        function parseExtractParams() {
            const params = [];
            if (textarea.value) {
                try {
                    const parsed = JSON.parse(textarea.value);
                    if (Array.isArray(parsed)) {
                        parsed.forEach(item => {
                            params.push({
                                name: item.name || '',
                                path: item.path || '',
                                description: item.description || ''
                            });
                        });
                    }
                } catch (e) {
                    console.error('Error parsing extract params:', e);
                }
            }
            if (params.length === 0) {
                params.push({ name: '', path: '', description: '' });
            }
            return params;
        }

        function updateTextarea() {
            const rows = container.querySelectorAll('tr');
            const params = [];
            rows.forEach(row => {
                const checkbox = row.querySelector('input[type="checkbox"]');
                if (checkbox && checkbox.checked) {
                    const nameInput = row.querySelector('.extract-name');
                    const pathInput = row.querySelector('.extract-path');
                    if (nameInput && pathInput && nameInput.value.trim()) {
                        params.push({
                            name: nameInput.value.trim(),
                            path: pathInput.value.trim(),
                            description: row.querySelector('.extract-description')?.value.trim() || ''
                        });
                    }
                }
            });
            textarea.value = JSON.stringify(params, null, 2);
        }

        function addRow(param = { name: '', path: '', description: '' }) {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td class="text-center align-middle">
                    <input type="checkbox" class="form-check-input extract-checkbox" checked>
                </td>
                <td><input type="text" class="form-control extract-name" value="${param.name}" placeholder="Name"></td>
                <td><input type="text" class="form-control extract-path font-monospace" value="${param.path}" placeholder="$.data.field"></td>
                <td><input type="text" class="form-control extract-description" value="${param.description}" placeholder="Description"></td>
                <td class="text-center align-middle">
                    <button type="button" class="btn btn-sm btn-link text-danger p-0 delete-param-btn">
                        <i class="bi bi-trash"></i>
                    </button>
                </td>
            `;

            const inputs = row.querySelectorAll('input');
            inputs.forEach(input => input.addEventListener('change', updateTextarea));

            const deleteBtn = row.querySelector('.delete-param-btn');
            deleteBtn.addEventListener('click', () => {
                row.remove();
                updateTextarea();
            });

            container.appendChild(row);
        }

        const params = parseExtractParams();
        params.forEach(param => addRow(param));

        addBtn.addEventListener('click', () => {
            addRow();
            updateTextarea();
        });
        selectAllCheckbox.addEventListener('change', () => {
            container.querySelectorAll('.extract-checkbox').forEach(cb => {
                cb.checked = selectAllCheckbox.checked;
            });
        });
        bulkEditBtn.addEventListener('click', () => {
            BulkEditManager.show('extract', '#extract-container');
        });

        const extractTableContainer = document.getElementById('extract-table-container');
        const extractTextContainer = document.getElementById('extract-text-container');
        const extractTextArea = document.getElementById('extract-text-area');
        const toggleExtractModeBtn = document.getElementById('toggle-extract-mode-btn');

        function updateExtractTextArea() {
            const params = [];
            container.querySelectorAll('tr').forEach(row => {
                const checkbox = row.querySelector('input[type="checkbox"]');
                if (checkbox && checkbox.checked) {
                    const nameInput = row.querySelector('.extract-name');
                    const pathInput = row.querySelector('.extract-path');
                    if (nameInput && pathInput && nameInput.value.trim()) {
                        params.push({
                            name: nameInput.value.trim(),
                            path: pathInput.value.trim(),
                            description: row.querySelector('.extract-description')?.value.trim() || ''
                        });
                    }
                }
            });
            extractTextArea.value = JSON.stringify(params, null, 2);
        }

        function parseExtractFromText() {
            try {
                return JSON.parse(extractTextArea.value);
            } catch (e) {
                console.error('Error parsing extract JSON:', e);
                return [];
            }
        }

        toggleExtractModeBtn.addEventListener('click', () => {
            const isTableVisible = extractTableContainer.style.display !== 'none';
            if (isTableVisible) {
                // Switch to text mode
                updateExtractTextArea();
                extractTableContainer.style.display = 'none';
                extractTextContainer.style.display = 'block';
                toggleExtractModeBtn.textContent = 'Table Edit';
            } else {
                // Switch to table mode
                container.innerHTML = '';
                const params = parseExtractFromText();
                if (params.length > 0) {
                    params.forEach(param => addRow(param));
                } else {
                    addRow();
                }
                updateTextarea();
                extractTableContainer.style.display = 'block';
                extractTextContainer.style.display = 'none';
                toggleExtractModeBtn.textContent = 'Key-Value Edit';
            }
        });

        document.getElementById('toggle-extract-table').addEventListener('click', () => {
            const containerDiv = document.getElementById('extract-table-container');
            containerDiv.style.display = containerDiv.style.display === 'none' ? 'block' : 'none';
        });
    }


    // 断言表格初始化
    function initValidationRulesTable() {
        const textarea = document.getElementById('{{ form.validation_rules_json.id_for_label }}');
        const container = document.getElementById('validation-container');
        const addBtn = document.getElementById('add-validation-btn');
        const selectAllCheckbox = document.getElementById('select-all-validation');
        const bulkEditBtn = document.getElementById('bulk-edit-validation-btn');

        function parseValidationRules() {
            const rules = [];
            if (textarea.value) {
                try {
                    const parsed = JSON.parse(textarea.value);
                    if (Array.isArray(parsed)) {
                        parsed.forEach(rule => {
                            const validator = Object.keys(rule)[0];
                            const value = rule[validator];
                            rules.push({
                                validator,
                                path: Array.isArray(value) ? value[0] : '',
                                value: Array.isArray(value) ? value[1] : value,
                                description: ''
                            });
                        });
                    }
                } catch (e) {
                    console.error('Error parsing validation rules:', e);
                }
            }
            if (rules.length === 0) {
                rules.push({ validator: 'eq', path: '', value: '', description: '' });
            }
            return rules;
        }

        function updateTextarea() {
            const rows = container.querySelectorAll('tr');
            const rules = [];
            rows.forEach(row => {
                const checkbox = row.querySelector('input[type="checkbox"]');
                if (checkbox && checkbox.checked) {
                    const typeInput = row.querySelector('.validation-type');
                    const pathInput = row.querySelector('.validation-path');
                    const valueInput = row.querySelector('.validation-value');

                    if (typeInput && pathInput && valueInput) {
                        const validator = typeInput.value;
                        const path = pathInput.value.trim();
                        const value = valueInput.value.trim();

                        if (path || value) {
                            const rule = {};
                            if (path && value) {
                                rule[validator] = [path, value];
                            } else if (path) {
                                rule[validator] = [path];
                            } else {
                                rule[validator] = [value];
                            }
                            rules.push(rule);
                        }
                    }
                }
            });
            textarea.value = JSON.stringify(rules, null, 2);
        }

        function addRow(rule = { validator: 'eq', path: '', value: '', description: '' }) {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td class="text-center align-middle">
                    <input type="checkbox" class="form-check-input validation-checkbox" checked>
                </td>
                <td>
                    <select class="form-select validation-type">
                        <option value="eq" ${rule.validator === 'eq' ? 'selected' : ''}>Equals</option>
                        <option value="ne" ${rule.validator === 'ne' ? 'selected' : ''}>Not Equals</option>
                        <option value="gt" ${rule.validator === 'gt' ? 'selected' : ''}>Greater Than</option>
                        <option value="lt" ${rule.validator === 'lt' ? 'selected' : ''}>Less Than</option>
                        <option value="contains" ${rule.validator === 'contains' ? 'selected' : ''}>Contains</option>
                        <option value="regex" ${rule.validator === 'regex' ? 'selected' : ''}>Regex</option>
                    </select>
                </td>
                <td><input type="text" class="form-control validation-path font-monospace" value="${rule.path}" placeholder="$.data.field"></td>
                <td><input type="text" class="form-control validation-value" value="${rule.value}" placeholder="Expected Value"></td>
                <td><input type="text" class="form-control validation-description" value="${rule.description}" placeholder="Description"></td>
                <td class="text-center align-middle">
                    <button type="button" class="btn btn-sm btn-link text-danger p-0 delete-param-btn">
                        <i class="bi bi-trash"></i>
                    </button>
                </td>
            `;

            const inputs = row.querySelectorAll('input, select');
            inputs.forEach(input => input.addEventListener('change', updateTextarea));

            const deleteBtn = row.querySelector('.delete-param-btn');
            deleteBtn.addEventListener('click', () => {
                row.remove();
                updateTextarea();
            });

            container.appendChild(row);
        }

        const rules = parseValidationRules();
        rules.forEach(rule => addRow(rule));

        addBtn.addEventListener('click', () => {
            addRow();
            updateTextarea();
        });
        selectAllCheckbox.addEventListener('change', () => {
            container.querySelectorAll('.validation-checkbox').forEach(cb => {
                cb.checked = selectAllCheckbox.checked;
            });
        });
        bulkEditBtn.addEventListener('click', () => {
            BulkEditManager.show('validation', '#validation-container');
        });

        const validationTableContainer = document.getElementById('validation-table-container');
        const validationTextContainer = document.getElementById('validation-text-container');
        const validationTextArea = document.getElementById('validation-text-area');
        const toggleValidationModeBtn = document.getElementById('toggle-validation-mode-btn');

        function updateValidationTextArea() {
            const rules = [];
            container.querySelectorAll('tr').forEach(row => {
                const checkbox = row.querySelector('input[type="checkbox"]');
                if (checkbox && checkbox.checked) {
                    const typeInput = row.querySelector('.validation-type');
                    const pathInput = row.querySelector('.validation-path');
                    const valueInput = row.querySelector('.validation-value');
                    if (typeInput && pathInput && valueInput) {
                        const validator = typeInput.value;
                        const path = pathInput.value.trim();
                        const value = valueInput.value.trim();
                        if (path || value) {
                            const rule = {};
                            if (path && value) {
                                rule[validator] = [path, value];
                            } else if (path) {
                                rule[validator] = [path];
                            } else {
                                rule[validator] = [value];
                            }
                            rules.push(rule);
                        }
                    }
                }
            });
            validationTextArea.value = JSON.stringify(rules, null, 2);
        }

        function parseValidationFromText() {
            try {
                return JSON.parse(validationTextArea.value);
            } catch (e) {
                console.error('Error parsing validation JSON:', e);
                return [];
            }
        }

        toggleValidationModeBtn.addEventListener('click', () => {
            const isTableVisible = validationTableContainer.style.display !== 'none';
            if (isTableVisible) {
                // Switch to text mode
                updateValidationTextArea();
                validationTableContainer.style.display = 'none';
                validationTextContainer.style.display = 'block';
                toggleValidationModeBtn.textContent = 'Table Edit';
            } else {
                // Switch to table mode
                container.innerHTML = '';
                const rulesData = parseValidationFromText();
                if (rulesData.length > 0) {
                    // Convert JSON format to rule objects
                    rulesData.forEach(ruleData => {
                        const validator = Object.keys(ruleData)[0];
                        const value = ruleData[validator];
                        addRow({
                            validator,
                            path: Array.isArray(value) ? value[0] : '',
                            value: Array.isArray(value) ? value[1] : value,
                            description: ''
                        });
                    });
                } else {
                    addRow();
                }
                updateTextarea();
                validationTableContainer.style.display = 'block';
                validationTextContainer.style.display = 'none';
                toggleValidationModeBtn.textContent = 'Key-Value Edit';
            }
        });

        document.getElementById('toggle-validation-table').addEventListener('click', () => {
            const containerDiv = document.getElementById('validation-table-container');
            containerDiv.style.display = containerDiv.style.display === 'none' ? 'block' : 'none';
        });
    }

    // 批量编辑应用按钮
    document.getElementById('applyBulkEditBtn').addEventListener('click', () => {
        BulkEditManager.applyChanges();
    });

    // 页面加载时初始化
    document.addEventListener('DOMContentLoaded', function() {
        toggleBodyFormat();
        initFormDataTable();
        initUrlParamsTable();
        initHeadersTable();
        initExtractParamsTable();
        initValidationRulesTable();
    });

    function toggleBodyFormat() {
        const jsonFormat = document.getElementById('format_json').checked;
        const jsonContainer = document.getElementById('json_body_container');
        const formDataContainer = document.getElementById('form_data_container');

        if (jsonFormat) {
            jsonContainer.style.display = 'block';
            formDataContainer.style.display = 'none';
        } else {
            jsonContainer.style.display = 'none';
            formDataContainer.style.display = 'block';
        }
    }
</script>
{% endblock %}

{% block extra_head %}
<style>
    .form-data-table th, .form-data-table td,
    .params-table th, .params-table td,
    .headers-table th, .headers-table td,
    .extract-table th, .extract-table td,
    .validation-table th, .validation-table td {
        padding: 0.5rem;
        vertical-align: middle;
    }

    .form-data-table .form-control,
    .form-data-table .form-select,
    .params-table .form-control,
    .headers-table .form-control,
    .extract-table .form-control,
    .validation-table .form-control,
    .validation-table .form-select {
        padding: 0.375rem 0.5rem;
        font-size: 0.875rem;
    }

    .form-data-table tbody tr:hover,
    .params-table tbody tr:hover,
    .headers-table tbody tr:hover,
    .extract-table tbody tr:hover,
    .validation-table tbody tr:hover {
        background-color: rgba(0, 0, 0, 0.02);
    }

    .form-check-input {
        cursor: pointer;
    }

    .extract-path,
    .validation-path {
        font-family: 'Courier New', monospace;
        font-size: 0.85rem;
    }

    /* Added improved text mode styling to match table mode */
    #params-text-container .card,
    #headers-text-container .card,
    #body-text-container .card,
    #extract-text-container .card,
    #validation-text-container .card {
        border: 1px solid #dee2e6;
        margin-bottom: 0;
    }

    #params-text-area,
    #headers-text-area,
    #body-text-area,
    #extract-text-area,
    #validation-text-area {
        min-height: 200px;
        font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
        font-size: 0.875rem;
        line-height: 1.5;
    }

    .btn-group .btn.active {
        background-color: #0d6efd;
        border-color: #0d6efd;
        color: white;
    }

    .btn-group .btn {
        border-right: none;
    }

    .btn-group .btn:last-child {
        border-right: 1px solid #dee2e6;
    }
</style>
{% endblock %}
</existing_code>
